name = "cargo"
version = "0.1.0"
dependencies = [
- "curl 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
- "docopt 0.6.23 (registry+https://github.com/rust-lang/crates.io-index)",
- "flate2 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
- "git2 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
- "glob 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "curl 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)",
+ "docopt 0.6.30 (registry+https://github.com/rust-lang/crates.io-index)",
+ "flate2 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
+ "git2 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)",
+ "glob 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
"hamcrest 0.1.0 (git+https://github.com/carllerche/hamcrest-rust.git)",
- "log 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
+ "log 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
"registry 0.1.0",
- "rustc-serialize 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
- "semver 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
- "tar 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
- "term 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
- "time 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
- "toml 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)",
- "url 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)",
+ "rustc-serialize 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)",
+ "semver 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
+ "tar 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
+ "term 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)",
+ "time 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
+ "toml 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)",
+ "url 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "curl"
-version = "0.1.7"
+version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"curl-sys 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
- "url 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)",
+ "url 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libz-sys 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
- "openssl-sys 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)",
- "pkg-config 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "openssl-sys 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)",
+ "pkg-config 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "docopt"
-version = "0.6.23"
+version = "0.6.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
- "regex 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)",
- "rustc-serialize 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "regex 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)",
+ "rustc-serialize 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "flate2"
-version = "0.1.3"
+version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"miniz-sys 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
[[package]]
name = "gcc"
-version = "0.1.3"
+version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "git2"
-version = "0.1.7"
+version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
- "libgit2-sys 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
- "time 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
- "url 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)",
+ "libgit2-sys 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
+ "url 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "glob"
-version = "0.1.4"
+version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "hamcrest"
version = "0.1.0"
-source = "git+https://github.com/carllerche/hamcrest-rust.git#4ae58daf0b3a853ffd3109e63f94d43e8e623769"
+source = "git+https://github.com/carllerche/hamcrest-rust.git#445dc78024c7d912d2e52dcd3ef3dfe2c8dbab47"
[[package]]
name = "libgit2-sys"
-version = "0.1.5"
+version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
- "libssh2-sys 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
- "openssl-sys 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)",
- "pkg-config 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "libssh2-sys 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
+ "openssl-sys 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)",
+ "pkg-config 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
[[package]]
name = "libssh2-sys"
-version = "0.1.1"
+version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libz-sys 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
- "openssl-sys 0.2.12 (registry+https://github.com/rust-lang/crates.io-index)",
- "pkg-config 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "openssl-sys 0.2.15 (registry+https://github.com/rust-lang/crates.io-index)",
+ "pkg-config 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
- "pkg-config 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "pkg-config 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "log"
-version = "0.1.7"
+version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
- "regex 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)",
+ "regex 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)",
]
+[[package]]
+name = "matches"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
[[package]]
name = "miniz-sys"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
- "gcc 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "gcc 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "openssl-sys"
-version = "0.2.12"
+version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libressl-pnacl-sys 2.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
- "pkg-config 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "pkg-config 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "pkg-config"
-version = "0.1.3"
+version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
[[package]]
name = "regex"
-version = "0.1.8"
+version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "registry"
version = "0.1.0"
dependencies = [
- "curl 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
- "rustc-serialize 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "curl 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)",
+ "rustc-serialize 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "rustc-serialize"
-version = "0.2.4"
+version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "semver"
-version = "0.1.9"
+version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "tar"
-version = "0.1.5"
+version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "term"
-version = "0.1.2"
+version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
- "log 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
+ "log 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "time"
-version = "0.1.9"
+version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
- "gcc 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "gcc 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "toml"
-version = "0.1.8"
+version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
- "rustc-serialize 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "rustc-serialize 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "url"
-version = "0.2.13"
+version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
- "rustc-serialize 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "matches 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
+ "rustc-serialize 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)",
]
struct Options {
flag_no_run: bool,
flag_package: Option<String>,
- flag_jobs: Option<uint>,
+ flag_jobs: Option<u32>,
flag_features: Vec<String>,
flag_bench: Option<String>,
flag_no_default_features: bool,
None => Ok(None),
Some(err) => {
Err(match err.exit {
- Some(ExitStatus(i)) => CliError::new("", i as uint),
+ Some(ExitStatus(i)) => CliError::new("", i as u32),
_ => CliError::from_boxed(box Human(err), 101)
})
}
#[derive(RustcDecodable)]
struct Options {
flag_package: Option<String>,
- flag_jobs: Option<uint>,
+ flag_jobs: Option<u32>,
flag_features: Vec<String>,
flag_no_default_features: bool,
flag_target: Option<String>,
";
pub fn execute(options: Options, shell: &mut MultiShell) -> CliResult<Option<()>> {
- debug!("executing; cmd=cargo-build; args={}", os::args());
+ debug!("executing; cmd=cargo-build; args={:?}", os::args());
shell.set_verbose(options.flag_verbose);
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path));
-#![feature(phase, macro_rules, old_orphan_check)]
+#![allow(unstable)]
extern crate "rustc-serialize" as rustc_serialize;
-#[phase(plugin, link)] extern crate log;
-#[phase(plugin, link)] extern crate cargo;
+extern crate cargo;
+#[macro_use] extern crate log;
use std::collections::BTreeSet;
use std::os;
execute_main_without_stdin(execute, true, USAGE)
}
-macro_rules! each_subcommand{ ($macro:ident) => ({
- $macro!(bench);
- $macro!(build);
- $macro!(clean);
- $macro!(config_for_key);
- $macro!(config_list);
- $macro!(doc);
- $macro!(fetch);
- $macro!(generate_lockfile);
- $macro!(git_checkout);
- $macro!(help);
- $macro!(locate_project);
- $macro!(login);
- $macro!(new);
- $macro!(owner);
- $macro!(package);
- $macro!(pkgid);
- $macro!(publish);
- $macro!(read_manifest);
- $macro!(run);
- $macro!(search);
- $macro!(test);
- $macro!(update);
- $macro!(verify_project);
- $macro!(version);
- $macro!(yank);
+macro_rules! each_subcommand{ ($mac:ident) => ({
+ $mac!(bench);
+ $mac!(build);
+ $mac!(clean);
+ $mac!(config_for_key);
+ $mac!(config_list);
+ $mac!(doc);
+ $mac!(fetch);
+ $mac!(generate_lockfile);
+ $mac!(git_checkout);
+ $mac!(help);
+ $mac!(locate_project);
+ $mac!(login);
+ $mac!(new);
+ $mac!(owner);
+ $mac!(package);
+ $mac!(pkgid);
+ $mac!(publish);
+ $mac!(read_manifest);
+ $mac!(run);
+ $mac!(search);
+ $mac!(test);
+ $mac!(update);
+ $mac!(verify_project);
+ $mac!(version);
+ $mac!(yank);
}) }
/**
on this top-level information.
*/
fn execute(flags: Flags, shell: &mut MultiShell) -> CliResult<Option<()>> {
- debug!("executing; cmd=cargo; args={}", os::args());
+ debug!("executing; cmd=cargo; args={:?}", os::args());
shell.set_verbose(flags.flag_verbose);
if flags.flag_list {
// allows us to only make suggestions that have an edit distance of
// 3 or less
.map(|c| (lev_distance(c.as_slice(), cmd), c))
- .filter(|&(d, _): &(uint, &String)| d < 4u)
+ .filter(|&(d, _): &(usize, &String)| d < 4)
.min_by(|&(d, _)| d) {
Some((_, c)) => {
Some(c.to_string())
match status {
Ok(ExitStatus(0)) => (),
Ok(ExitStatus(i)) => {
- handle_error(CliError::new("", i as uint), shell)
+ handle_error(CliError::new("", i as u32), shell)
}
Ok(ExitSignal(i)) => {
let msg = format!("subcommand failed with signal: {}", i);
- handle_error(CliError::new(msg, i as uint), shell)
+ handle_error(CliError::new(msg, i as u32), shell)
}
Err(io::IoError{kind, ..}) if kind == io::FileNotFound =>
handle_error(CliError::new("No such subcommand", 127), shell),
pub fn execute(options: Options, shell: &mut MultiShell) -> CliResult<Option<()>> {
shell.set_verbose(options.flag_verbose);
- debug!("executing; cmd=cargo-clean; args={}", os::args());
+ debug!("executing; cmd=cargo-clean; args={:?}", os::args());
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path));
let mut opts = ops::CleanOptions {
}));
if args.flag_human {
- println!("{}", value);
+ println!("{:?}", value);
Ok(None)
} else {
let mut map = HashMap::new();
if args.flag_human {
for (key, value) in configs.iter() {
- println!("{} = {}", key, value);
+ println!("{} = {:?}", key, value);
}
Ok(None)
} else {
#[derive(RustcDecodable)]
struct Options {
flag_features: Vec<String>,
- flag_jobs: Option<uint>,
+ flag_jobs: Option<u32>,
flag_manifest_path: Option<String>,
flag_no_default_features: bool,
flag_no_deps: bool,
";
pub fn execute(options: Options, shell: &mut MultiShell) -> CliResult<Option<()>> {
- debug!("executing; cmd=cargo-generate-lockfile; args={}", os::args());
+ debug!("executing; cmd=cargo-generate-lockfile; args={:?}", os::args());
shell.set_verbose(options.flag_verbose);
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path));
let mut source = GitSource::new(&source_id, &mut config);
try!(source.update().map_err(|e| {
- CliError::new(format!("Couldn't update {}: {}", source, e), 1)
+ CliError::new(format!("Couldn't update {:?}: {:?}", source, e), 1)
}));
Ok(None)
let token = match options.arg_token.clone() {
Some(token) => token,
None => {
- let err = (|| {
+ let err = (|:| {
let config = try!(Config::new(shell, None, None));
let src = try!(SourceId::for_central());
let mut src = RegistrySource::new(&src, &config);
Options:
-h, --help Print this message
--vcs <vcs> Initialize a new repository for the given version
- control system (git or hg) or do not initialize any version
- control at all (none) overriding a global configuration.
+ control system (git or hg) or do not initialize any version
+ control at all (none) overriding a global configuration.
--travis Create a .travis.yml file
--bin Use a binary instead of a library template
-v, --verbose Use verbose output
";
pub fn execute(options: Options, shell: &mut MultiShell) -> CliResult<Option<()>> {
- debug!("executing; cmd=cargo-new; args={}", os::args());
+ debug!("executing; cmd=cargo-new; args={:?}", os::args());
shell.set_verbose(options.flag_verbose);
let Options { flag_travis, flag_bin, arg_path, flag_vcs, .. } = options;
struct Options {
flag_bin: Option<String>,
flag_example: Option<String>,
- flag_jobs: Option<uint>,
+ flag_jobs: Option<u32>,
flag_features: Vec<String>,
flag_no_default_features: bool,
flag_target: Option<String>,
None => Ok(None),
Some(err) => {
Err(match err.exit {
- Some(ExitStatus(i)) => CliError::from_boxed(box err, i as uint),
+ Some(ExitStatus(i)) => CliError::from_boxed(box err, i as u32),
_ => CliError::from_boxed(box err, 101),
})
}
struct Options {
arg_args: Vec<String>,
flag_features: Vec<String>,
- flag_jobs: Option<uint>,
+ flag_jobs: Option<u32>,
flag_manifest_path: Option<String>,
flag_test: Option<String>,
flag_no_default_features: bool,
None => Ok(None),
Some(err) => {
Err(match err.exit {
- Some(ExitStatus(i)) => CliError::new("", i as uint),
+ Some(ExitStatus(i)) => CliError::new("", i as u32),
_ => CliError::from_boxed(box Human(err), 101)
})
}
";
pub fn execute(options: Options, shell: &mut MultiShell) -> CliResult<Option<()>> {
- debug!("executing; cmd=cargo-update; args={}", os::args());
+ debug!("executing; cmd=cargo-update; args={:?}", os::args());
shell.set_verbose(options.flag_verbose);
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path));
";
pub fn execute(_: Options, _: &mut MultiShell) -> CliResult<Option<()>> {
- debug!("executing; cmd=cargo-version; args={}", os::args());
+ debug!("executing; cmd=cargo-version; args={:?}", os::args());
println!("{}", cargo::version());
use std::hash;
-use std::fmt::{self, Show, Formatter};
use semver::Version;
use rustc_serialize::{Encoder,Encodable};
use util::{CargoResult, human};
/// Contains all the informations about a package, as loaded from a Cargo.toml.
-#[derive(PartialEq,Clone)]
+#[derive(PartialEq,Clone, Show)]
pub struct Manifest {
summary: Summary,
targets: Vec<Target>,
metadata: ManifestMetadata,
}
-impl Show for Manifest {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- write!(f, "Manifest({}, targets={}, target_dir={}, \
- build={})",
- self.summary, self.targets, self.target_dir.display(),
- self.build)
- }
-}
-
/// General metadata about a package which is just blindly uploaded to the
/// registry.
///
/// validated by cargo itself, but rather it is up to the registry when uploaded
/// to validate these fields. Cargo will itself accept any valid TOML
/// specification for these values.
-#[derive(PartialEq, Clone)]
+#[derive(PartialEq, Clone, Show)]
pub struct ManifestMetadata {
pub authors: Vec<String>,
pub keywords: Vec<String>,
build: Option<Vec<String>>, // TODO: deprecated, remove
}
-impl<E, S: Encoder<E>> Encodable<S, E> for Manifest {
- fn encode(&self, s: &mut S) -> Result<(), E> {
+impl Encodable for Manifest {
+ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
SerializedManifest {
name: self.summary.get_name().to_string(),
version: self.summary.get_version().to_string(),
#[derive(RustcEncodable, RustcDecodable, Clone, PartialEq, Show)]
pub struct Profile {
env: String, // compile, test, dev, bench, etc.
- opt_level: uint,
+ opt_level: u32,
lto: bool,
- codegen_units: Option<uint>, // None = use rustc default
+ codegen_units: Option<u32>, // None = use rustc default
debug: bool,
rpath: bool,
test: bool,
self.for_host
}
- pub fn get_opt_level(&self) -> uint {
+ pub fn get_opt_level(&self) -> u32 {
self.opt_level
}
self.lto
}
- pub fn get_codegen_units(&self) -> Option<uint> {
+ pub fn get_codegen_units(&self) -> Option<u32> {
self.codegen_units
}
self.dest.as_ref().map(|d| d.as_slice())
}
- pub fn opt_level(mut self, level: uint) -> Profile {
+ pub fn opt_level(mut self, level: u32) -> Profile {
self.opt_level = level;
self
}
self
}
- pub fn codegen_units(mut self, units: Option<uint>) -> Profile {
+ pub fn codegen_units(mut self, units: Option<u32>) -> Profile {
self.codegen_units = units;
self
}
}
}
-impl<H: hash::Writer> hash::Hash<H> for Profile {
+impl<H: hash::Writer + hash::Hasher> hash::Hash<H> for Profile {
fn hash(&self, into: &mut H) {
// Be sure to match all fields explicitly, but ignore those not relevant
// to the actual hash of a profile.
}
/// Informations about a binary, a library, an example, etc. that is part of the package.
-#[derive(Clone, Hash, PartialEq)]
+#[derive(Clone, Hash, PartialEq, Show)]
pub struct Target {
kind: TargetKind,
name: String,
metadata: Option<Metadata>
}
-impl<E, S: Encoder<E>> Encodable<S, E> for Target {
- fn encode(&self, s: &mut S) -> Result<(), E> {
+impl Encodable for Target {
+ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
let kind = match self.kind {
TargetKind::Lib(ref kinds) => kinds.iter().map(|k| k.crate_type()).collect(),
TargetKind::Bin => vec!("bin"),
}
}
-impl Show for Target {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- write!(f, "{}(name={}, path={}, profile={})", self.kind, self.name,
- self.src_path.display(), self.profile)
- }
-}
-
-
impl Manifest {
pub fn new(summary: Summary, targets: Vec<Target>,
target_dir: Path, doc_dir: Path,
-use std::fmt::{self, Show, Formatter};
+use std::fmt::{self, Formatter};
use std::hash;
use std::slice;
use semver::Version;
///
/// A package is a `Cargo.toml` file, plus all the files that are part of it.
// TODO: Is manifest_path a relic?
-#[derive(Clone)]
+#[derive(Clone, Show)]
pub struct Package {
// The package's manifest
manifest: Manifest,
manifest_path: String,
}
-impl<E, S: Encoder<E>> Encodable<S, E> for Package {
- fn encode(&self, s: &mut S) -> Result<(), E> {
+impl Encodable for Package {
+ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
let manifest = self.get_manifest();
let summary = manifest.get_summary();
let package_id = summary.get_package_id();
}
}
-impl Show for Package {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+impl fmt::String for Package {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.get_summary().get_package_id())
}
}
impl Eq for Package {}
-impl hash::Hash for Package {
- fn hash(&self, into: &mut hash::sip::SipState) {
+impl<H: hash::Writer + hash::Hasher> hash::Hash<H> for Package {
+ fn hash(&self, into: &mut H) {
self.get_package_id().hash(into)
}
}
PackageSet { packages: packages.to_vec() }
}
- pub fn len(&self) -> uint {
+ pub fn len(&self) -> usize {
self.packages.len()
}
use std::cmp::Ordering;
use std::error::{Error, FromError};
-use std::fmt::{self, Show, Formatter};
-use std::hash::Hash;
+use std::fmt::{self, Formatter};
+use std::hash::{Hash, SipHasher};
use std::hash;
use std::sync::Arc;
use core::source::SourceId;
/// Identifier for a specific version of a package in a specific source.
-#[derive(Clone)]
+#[derive(Clone, Show)]
pub struct PackageId {
inner: Arc<PackageIdInner>,
}
-#[derive(PartialEq, PartialOrd, Eq, Ord)]
+#[derive(PartialEq, PartialOrd, Eq, Ord, Show)]
struct PackageIdInner {
name: String,
version: semver::Version,
source_id: SourceId,
}
-impl<E, S: Encoder<E>> Encodable<S, E> for PackageId {
- fn encode(&self, s: &mut S) -> Result<(), E> {
+impl Encodable for PackageId {
+ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
let source = self.inner.source_id.to_url();
let encoded = format!("{} {} ({})", self.inner.name, self.inner.version,
source);
}
}
-impl<E, D: Decoder<E>> Decodable<D, E> for PackageId {
- fn decode(d: &mut D) -> Result<PackageId, E> {
+impl Decodable for PackageId {
+ fn decode<D: Decoder>(d: &mut D) -> Result<PackageId, D::Error> {
let string: String = try!(Decodable::decode(d));
let regex = Regex::new(r"^([^ ]+) ([^ ]+) \(([^\)]+)\)$").unwrap();
let captures = regex.captures(string.as_slice()).expect("invalid serialized PackageId");
}
}
-impl<S: hash::Writer> Hash<S> for PackageId {
+impl<S: hash::Writer + hash::Hasher> Hash<S> for PackageId {
fn hash(&self, state: &mut S) {
self.inner.name.hash(state);
self.inner.version.to_string().hash(state);
}
impl FromError<PackageIdError> for Box<CargoError> {
- fn from_error(t: PackageIdError) -> Box<CargoError> { box t }
+ fn from_error(t: PackageIdError) -> Box<CargoError> { Box::new(t) }
}
-#[derive(PartialEq, Hash, Clone, RustcEncodable)]
+#[derive(PartialEq, Hash, Clone, RustcEncodable, Show)]
pub struct Metadata {
pub metadata: String,
pub extra_filename: String
}
impl Metadata {
- pub fn mix<T: Hash>(&mut self, t: &T) {
+ pub fn mix<T: Hash<SipHasher>>(&mut self, t: &T) {
let new_metadata = short_hash(&(self.metadata.as_slice(), t));
self.extra_filename = format!("-{}", new_metadata);
self.metadata = new_metadata;
}
}
-impl Show for PackageId {
+impl fmt::String for PackageId {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
try!(write!(f, "{} v{}", self.inner.name, self.inner.version));
use core::PackageId;
use util::{CargoResult, ToUrl, human, ToSemver, ChainError};
-#[derive(Clone, PartialEq, Eq)]
+#[derive(Clone, PartialEq, Eq, Show)]
pub struct PackageIdSpec {
name: String,
version: Option<Version>,
}
-impl fmt::Show for PackageIdSpec {
+impl fmt::String for PackageIdSpec {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut printed_name = false;
match self.url {
impl Registry for Vec<Summary> {
fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> {
- debug!("querying for {}, summaries={}", dep,
- self.iter().map(|s| s.get_package_id().to_string()).collect::<Vec<String>>());
+ debug!("querying for {:?}, summaries={:?}", dep,
+ self.iter().map(|s| s.get_package_id()).collect::<Vec<_>>());
Ok(self.iter().filter(|summary| dep.matches(*summary))
.map(|summary| summary.clone()).collect())
}
pub fn get(&mut self, package_ids: &[PackageId]) -> CargoResult<Vec<Package>> {
- log!(5, "getting packags; sources={}; ids={}", self.sources.len(),
+ log!(5, "getting packags; sources={}; ids={:?}", self.sources.len(),
package_ids);
// TODO: Only call source with package ID if the package came from the
// TODO: Return earlier if fail
assert!(package_ids.len() == ret.len(),
- "could not get packages from registry; ids={}; ret={}",
+ "could not get packages from registry; ids={:?}; ret={:?}",
package_ids, ret);
Ok(ret)
}
pub fn register_lock(&mut self, id: PackageId, deps: Vec<PackageId>) {
- let source = id.get_source_id().clone();
- let sub_map = match self.locked.entry(&source) {
+ let sub_map = match self.locked.entry(id.get_source_id().clone()) {
Occupied(e) => e.into_mut(),
Vacant(e) => e.insert(HashMap::new()),
};
- let name = id.get_name().to_string();
- let sub_vec = match sub_map.entry(&name) {
+ let sub_vec = match sub_map.entry(id.get_name().to_string()) {
Occupied(e) => e.into_mut(),
Vacant(e) => e.insert(Vec::new()),
};
impl Registry for RegistryBuilder {
fn query(&mut self, dep: &Dependency) -> CargoResult<Vec<Summary>> {
- debug!("querying; dep={}", dep);
+ debug!("querying; dep={:?}", dep);
let overrides = self.query_overrides(dep);
let packages = self.package.as_ref().unwrap_or(&packages);
{
- let register_pkg = |pkg: &EncodableDependency| -> CargoResult<()> {
+ let mut register_pkg = |&mut: pkg: &EncodableDependency|
+ -> CargoResult<()> {
let pkgid = try!(pkg.to_package_id(default));
let precise = pkgid.get_source_id().get_precise()
.map(|s| s.to_string());
}
{
- let add_dependencies = |pkg: &EncodableDependency| -> CargoResult<()> {
+ let mut add_dependencies = |&mut: pkg: &EncodableDependency|
+ -> CargoResult<()> {
let package_id = try!(pkg.to_package_id(default));
let deps = match pkg.dependencies {
source: Option<SourceId>
}
-impl<E, S: Encoder<E>> Encodable<S, E> for EncodablePackageId {
- fn encode(&self, s: &mut S) -> Result<(), E> {
+impl Encodable for EncodablePackageId {
+ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
let mut out = format!("{} {}", self.name, self.version);
if let Some(ref s) = self.source {
out.push_str(format!(" ({})", s.to_url()).as_slice());
}
}
-impl<E, D: Decoder<E>> Decodable<D, E> for EncodablePackageId {
- fn decode(d: &mut D) -> Result<EncodablePackageId, E> {
+impl Decodable for EncodablePackageId {
+ fn decode<D: Decoder>(d: &mut D) -> Result<EncodablePackageId, D::Error> {
let string: String = try!(Decodable::decode(d));
let regex = Regex::new(r"^([^ ]+) ([^ ]+)(?: \(([^\)]+)\))?$").unwrap();
let captures = regex.captures(string.as_slice())
}
}
-impl<E, S: Encoder<E>> Encodable<S, E> for Resolve {
- fn encode(&self, s: &mut S) -> Result<(), E> {
+impl Encodable for Resolve {
+ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
let mut ids: Vec<&PackageId> = self.graph.iter().collect();
ids.sort();
spec: &PackageIdSpec) {
let mut version_cnt = HashMap::new();
for id in ids.iter() {
- match version_cnt.entry(&id.get_version()) {
- Vacant(e) => { e.insert(1u); }
- Occupied(e) => *e.into_mut() += 1u,
+ match version_cnt.entry(id.get_version()) {
+ Vacant(e) => { e.insert(1); }
+ Occupied(e) => *e.into_mut() += 1,
}
}
for id in ids.iter() {
/// Builds the list of all packages required to build the first argument.
pub fn resolve<R: Registry>(summary: &Summary, method: Method,
registry: &mut R) -> CargoResult<Resolve> {
- log!(5, "resolve; summary={}", summary);
+ log!(5, "resolve; summary={:?}", summary);
let mut cx = Context {
resolve: Resolve::new(summary.get_package_id().clone()),
activations: HashMap::new(),
visited: Rc::new(RefCell::new(HashSet::new())),
};
- let _p = profile::start(format!("resolving: {}", summary));
+ let _p = profile::start(format!("resolving: {:?}", summary));
cx.activations.insert((summary.get_name().to_string(),
summary.get_source_id().clone()),
vec![Rc::new(summary.clone())]);
parent: &Summary,
platform: Option<&'a str>,
deps: &'a [(&Dependency, Vec<Rc<Summary>>, Vec<String>)],
- cur: uint) -> CargoResult<CargoResult<Context>> {
+ cur: usize) -> CargoResult<CargoResult<Context>> {
if cur == deps.len() { return Ok(Ok(cx)) }
let (dep, ref candidates, ref features) = deps[cur];
let method = Method::Required(false, features.as_slice(),
let early_return = {
my_cx.resolve.graph.link(parent.get_package_id().clone(),
candidate.get_package_id().clone());
- let prev = match my_cx.activations.entry(&key) {
+ let prev = match my_cx.activations.entry(key.clone()) {
Occupied(e) => e.into_mut(),
Vacant(e) => e.insert(Vec::new()),
};
Err(e) => { last_err = Some(e); }
}
}
- log!(5, "{}[{}]>{} -- {}", parent.get_name(), cur, dep.get_name(), last_err);
+ log!(5, "{}[{}]>{} -- {:?}", parent.get_name(), cur, dep.get_name(),
+ last_err);
// Oh well, we couldn't activate any of the candidates, so we just can't
// activate this dependency at all
v.get_version()).as_slice());
}
- msg.push_str(format!("\n possible versions to select: {}",
- candidates.iter().map(|v| v.get_version())
- .collect::<Vec<_>>()).as_slice());
+ msg.push_str(&format!("\n possible versions to select: {}",
+ candidates.iter()
+ .map(|v| v.get_version())
+ .map(|v| v.to_string())
+ .collect::<Vec<_>>()
+ .connect(", "))[]);
Err(human(msg))
}
// Record what list of features is active for this package.
if used_features.len() > 0 {
let pkgid = parent.get_package_id();
- match cx.resolve.features.entry(pkgid) {
+ match cx.resolve.features.entry(pkgid.clone()) {
Occupied(entry) => entry.into_mut(),
Vacant(entry) => entry.insert(HashSet::new()),
}.extend(used_features.into_iter());
match parts.next() {
Some(feat) => {
let package = feat_or_package;
- match deps.entry(package) {
+ match deps.entry(package.to_string()) {
Occupied(e) => e.into_mut(),
Vacant(e) => e.insert(Vec::new()),
}.push(feat.to_string());
}
}
None => {
- match deps.entry(feat) {
+ match deps.entry(feat.to_string()) {
Occupied(..) => {} // already activated
Vacant(e) => { e.insert(Vec::new()); }
}
-use term::{Terminal, TerminfoTerminal, color};
-use term::color::{Color, BLACK, RED, GREEN, YELLOW};
-use term::attr::{Attr, Bold};
+use std::fmt;
use std::io::{IoResult, stderr};
-use std::fmt::Show;
+
+use term::Attr;
+use term::color::{Color, BLACK, RED, GREEN, YELLOW};
+use term::{Terminal, TerminfoTerminal, color};
use self::AdequateTerminal::{NoColor, Colored};
verbose: bool
}
-pub type Callback<'a> = |&mut MultiShell|:'a -> IoResult<()>;
-
struct UghWhyIsThisNecessary {
inner: Box<Writer + Send>,
}
self.out().say(message, color)
}
- pub fn status<T: Show, U: Show>(&mut self, status: T, message: U) -> IoResult<()> {
+ pub fn status<T, U>(&mut self, status: T, message: U) -> IoResult<()>
+ where T: fmt::String, U: fmt::String
+ {
self.out().say_status(status, message, GREEN)
}
- pub fn verbose(&mut self, callback: Callback) -> IoResult<()> {
+ pub fn verbose<F>(&mut self, mut callback: F) -> IoResult<()>
+ where F: FnMut(&mut MultiShell) -> IoResult<()>
+ {
if self.verbose { return callback(self) }
Ok(())
}
- pub fn concise(&mut self, callback: Callback) -> IoResult<()> {
+ pub fn concise<F>(&mut self, mut callback: F) -> IoResult<()>
+ where F: FnMut(&mut MultiShell) -> IoResult<()>
+ {
if !self.verbose { return callback(self) }
Ok(())
}
}
}
-pub type ShellCallback<'a> = |&mut Shell|:'a -> IoResult<()>;
-
impl Shell {
pub fn create(out: Box<Writer + Send>, config: ShellConfig) -> Shell {
let out = UghWhyIsThisNecessary { inner: out };
terminal: Colored(t),
config: config
}).unwrap_or_else(|| {
- Shell { terminal: NoColor(box stderr()), config: config }
+ Shell { terminal: NoColor(Box::new(stderr())), config: config }
})
} else {
Shell { terminal: NoColor(out.inner), config: config }
}
}
- pub fn verbose(&mut self, callback: ShellCallback) -> IoResult<()> {
+ pub fn verbose<F>(&mut self, mut callback: F) -> IoResult<()>
+ where F: FnMut(&mut Shell) -> IoResult<()>
+ {
if self.config.verbose { return callback(self) }
Ok(())
}
- pub fn concise(&mut self, callback: ShellCallback) -> IoResult<()> {
+ pub fn concise<F>(&mut self, mut callback: F) -> IoResult<()>
+ where F: FnMut(&mut Shell) -> IoResult<()>
+ {
if !self.config.verbose { return callback(self) }
Ok(())
}
Ok(())
}
- pub fn say_status<T: Show, U: Show>(&mut self, status: T, message: U,
- color: Color) -> IoResult<()> {
+ pub fn say_status<T, U>(&mut self, status: T, message: U, color: Color)
+ -> IoResult<()>
+ where T: fmt::String, U: fmt::String
+ {
try!(self.reset());
if color != BLACK { try!(self.fg(color)); }
- if self.supports_attr(Bold) { try!(self.attr(Bold)); }
+ if self.supports_attr(Attr::Bold) { try!(self.attr(Attr::Bold)); }
try!(self.write_str(format!("{:>12}", status).as_slice()));
try!(self.reset());
try!(self.write_line(format!(" {}", message).as_slice()));
fn reset(&mut self) -> IoResult<()> {
match self.terminal {
- Colored(ref mut c) => c.reset(),
+ Colored(ref mut c) => c.reset().map(|_| ()),
NoColor(_) => Ok(())
}
}
use std::collections::hash_map::{HashMap, Values, IterMut};
use std::cmp::Ordering;
-use std::fmt::{self, Show, Formatter};
+use std::fmt::{self, Formatter};
use std::hash;
use std::mem;
use std::sync::Arc;
type Error = Box<CargoError + Send>;
/// Unique identifier for a source of packages.
-#[derive(Clone, Eq)]
+#[derive(Clone, Eq, Show)]
pub struct SourceId {
inner: Arc<SourceIdInner>,
}
-#[derive(Eq, Clone)]
+#[derive(Eq, Clone, Show)]
struct SourceIdInner {
url: Url,
kind: Kind,
pub fn load<'a>(&self, config: &'a Config) -> Box<Source+'a> {
log!(5, "loading SourceId; {}", self);
match self.inner.kind {
- Kind::Git(..) => box GitSource::new(self, config) as Box<Source+'a>,
+ Kind::Git(..) => Box::new(GitSource::new(self, config)) as Box<Source>,
Kind::Path => {
let path = match self.inner.url.to_file_path() {
Ok(p) => p,
Err(()) => panic!("path sources cannot be remote"),
};
- box PathSource::new(&path, self) as Box<Source>
+ Box::new(PathSource::new(&path, self)) as Box<Source>
},
Kind::Registry => {
- box RegistrySource::new(self, config) as Box<Source+'a>
+ Box::new(RegistrySource::new(self, config)) as Box<Source>
}
}
}
}
}
-impl<E, S: Encoder<E>> Encodable<S, E> for SourceId {
- fn encode(&self, s: &mut S) -> Result<(), E> {
+impl Encodable for SourceId {
+ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
if self.is_path() {
s.emit_option_none()
} else {
}
}
-impl<E, D: Decoder<E>> Decodable<D, E> for SourceId {
- fn decode(d: &mut D) -> Result<SourceId, E> {
+impl Decodable for SourceId {
+ fn decode<D: Decoder>(d: &mut D) -> Result<SourceId, D::Error> {
let string: String = Decodable::decode(d).ok().expect("Invalid encoded SourceId");
Ok(SourceId::from_url(string))
}
}
-impl Show for SourceId {
+impl fmt::String for SourceId {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match *self.inner {
- SourceIdInner { kind: Kind::Path, ref url, .. } => url.fmt(f),
+ SourceIdInner { kind: Kind::Path, ref url, .. } => {
+ fmt::String::fmt(url, f)
+ }
SourceIdInner { kind: Kind::Git(ref reference), ref url,
ref precise, .. } => {
try!(write!(f, "{}{}", url, url_ref(reference)));
}
}
-impl<S: hash::Writer> hash::Hash<S> for SourceId {
+impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for SourceId {
fn hash(&self, into: &mut S) {
self.inner.kind.hash(into);
match *self.inner {
self.map.insert(id.clone(), source);
}
- pub fn len(&self) -> uint {
+ pub fn len(&self) -> usize {
self.map.len()
}
-#![crate_name="cargo"]
-#![crate_type="rlib"]
-
-#![feature(macro_rules, phase, default_type_params, unboxed_closures)]
-#![feature(slicing_syntax, old_orphan_check, associated_types)]
#![deny(unused)]
+#![allow(unstable)]
#![cfg_attr(test, deny(warnings))]
extern crate libc;
extern crate regex;
extern crate term;
extern crate time;
-#[phase(plugin, link)] extern crate log;
+#[macro_use] extern crate log;
extern crate curl;
extern crate docopt;
extern crate registry;
use std::error::Error;
-use std::fmt;
use std::io::stdio::{stdout_raw, stderr_raw};
use std::io::{self, stdout, stderr};
use std::os;
-use rustc_serialize::{Decoder, Encoder, Decodable, Encodable};
+use rustc_serialize::{Decodable, Encodable};
use rustc_serialize::json::{self, Json};
use docopt::Docopt;
pub mod sources;
pub mod util;
-pub trait RepresentsJSON : Decodable<json::Decoder, json::DecoderError> {}
-impl<T: Decodable<json::Decoder, json::DecoderError>> RepresentsJSON for T {}
-
pub fn execute_main<T, U, V>(
exec: fn(T, U, &mut MultiShell) -> CliResult<Option<V>>,
options_first: bool,
usage: &str)
- where V: for<'a> Encodable<json::Encoder<'a>, fmt::Error>,
- T: Decodable<docopt::Decoder, docopt::Error>,
- U: RepresentsJSON
+ where V: Encodable, T: Decodable, U: Decodable
{
- process::<V>(|rest, shell| call_main(exec, shell, usage, rest, options_first));
+ process::<V, _>(|rest, shell| {
+ call_main(exec, shell, usage, rest, options_first)
+ });
}
pub fn call_main<T, U, V>(
usage: &str,
args: &[String],
options_first: bool) -> CliResult<Option<V>>
- where V: for<'a> Encodable<json::Encoder<'a>, fmt::Error>,
- T: Decodable<docopt::Decoder, docopt::Error>,
- U: RepresentsJSON
+ where V: Encodable, T: Decodable, U: Decodable
{
let flags = try!(flags_from_args::<T>(usage, args, options_first));
let json = try!(json_from_stdin::<U>());
exec: fn(T, &mut MultiShell) -> CliResult<Option<V>>,
options_first: bool,
usage: &str)
- where V: for<'a> Encodable<json::Encoder<'a>, fmt::Error>,
- T: Decodable<docopt::Decoder, docopt::Error>
+ where V: Encodable, T: Decodable
{
- process::<V>(|rest, shell| call_main_without_stdin(exec, shell, usage, rest,
- options_first));
+ process::<V, _>(|rest, shell| {
+ call_main_without_stdin(exec, shell, usage, rest, options_first)
+ });
}
pub fn execute_main_with_args_and_without_stdin<T, V>(
options_first: bool,
usage: &str,
args: &[String])
- where V: for<'a> Encodable<json::Encoder<'a>, fmt::Error>,
- T: Decodable<docopt::Decoder, docopt::Error>
+ where V: Encodable, T: Decodable
{
let mut shell = shell(true);
usage: &str,
args: &[String],
options_first: bool) -> CliResult<Option<V>>
- where V: for<'a> Encodable<json::Encoder<'a>, fmt::Error>,
- T: Decodable<docopt::Decoder, docopt::Error>
+ where V: Encodable, T: Decodable
{
let flags = try!(flags_from_args::<T>(usage, args, options_first));
exec(flags, shell)
}
-fn process<V>(callback: |&[String], &mut MultiShell| -> CliResult<Option<V>>)
- where V: for<'a> Encodable<json::Encoder<'a>, fmt::Error>
+fn process<V, F>(mut callback: F)
+ where F: FnMut(&[String], &mut MultiShell) -> CliResult<Option<V>>,
+ V: Encodable
{
let mut shell = shell(true);
process_executed(callback(os::args().as_slice(), &mut shell), &mut shell)
pub fn process_executed<T>(result: CliResult<Option<T>>,
shell: &mut MultiShell)
- where T: for<'a> Encodable<json::Encoder<'a>, fmt::Error>
+ where T: Encodable
{
match result {
Err(e) => handle_error(e, shell),
pub fn shell(verbose: bool) -> MultiShell {
let tty = stderr_raw().isatty();
- let stderr = box stderr() as Box<Writer + Send>;
+ let stderr = Box::new(stderr()) as Box<Writer + Send>;
let config = ShellConfig { color: true, verbose: verbose, tty: tty };
let err = Shell::create(stderr, config);
let tty = stdout_raw().isatty();
- let stdout = box stdout() as Box<Writer + Send>;
+ let stdout = Box::new(stdout()) as Box<Writer + Send>;
let config = ShellConfig { color: true, verbose: verbose, tty: tty };
let out = Shell::create(stdout, config);
}
pub fn handle_error(err: CliError, shell: &mut MultiShell) {
- log!(4, "handle_error; err={}", err);
+ log!(4, "handle_error; err={:?}", err);
let CliError { error, exit_code, unknown } = err;
let verbose = shell.get_verbose();
}
}
- std::os::set_exit_status(exit_code as int);
+ std::os::set_exit_status(exit_code as isize);
}
fn handle_cause(mut err: &Error, shell: &mut MultiShell) {
fn flags_from_args<'a, T>(usage: &str, args: &[String],
options_first: bool) -> CliResult<T>
- where T: Decodable<docopt::Decoder, docopt::Error> {
+ where T: Decodable
+{
struct CargoDocoptError { err: docopt::Error }
impl Error for CargoDocoptError {
fn description(&self) -> &str {
})
}
-fn json_from_stdin<T: RepresentsJSON>() -> CliResult<T> {
+fn json_from_stdin<T: Decodable>() -> CliResult<T> {
let mut reader = io::stdin();
let input = try!(reader.read_to_string().map_err(|_| {
CliError::new("Standard in did not exist or was not UTF-8", 1)
pub env: &'a str,
pub shell: &'a mut MultiShell,
/// Number of concurrent jobs to use.
- pub jobs: Option<uint>,
+ pub jobs: Option<u32>,
/// The target platform to compile for (example: `i686-unknown-linux-gnu`).
pub target: Option<&'a str>,
/// True if dev-dependencies must be compiled.
(packages, resolved_with_overrides, registry.move_sources())
};
- debug!("packages={}", packages);
+ debug!("packages={:?}", packages);
let to_build = match spec {
Some(spec) => {
fn source_ids_from_config(configs: &HashMap<String, config::ConfigValue>,
cur_path: Path) -> CargoResult<Vec<SourceId>> {
- debug!("loaded config; configs={}", configs);
+ debug!("loaded config; configs={:?}", configs);
let config_paths = match configs.get("paths") {
Some(cfg) => cfg,
pub path: &'a str,
}
-impl<E, D: Decoder<E>> Decodable<D, E> for VersionControl {
- fn decode(d: &mut D) -> Result<VersionControl, E> {
+impl Decodable for VersionControl {
+ fn decode<D: Decoder>(d: &mut D) -> Result<VersionControl, D::Error> {
Ok(match try!(d.read_str()).as_slice() {
"git" => VersionControl::Git,
"hg" => VersionControl::Hg,
if all_packages.is_empty() {
Err(human(format!("Could not find Cargo.toml in `{}`", path.display())))
} else {
- log!(5, "all packages: {}", all_packages);
+ log!(5, "all packages: {:?}", all_packages);
Ok(all_packages.into_iter().collect())
}
}
-fn walk(path: &Path,
- callback: |&Path| -> CargoResult<bool>) -> CargoResult<()> {
+fn walk<F>(path: &Path, mut callback: F) -> CargoResult<()>
+ where F: FnMut(&Path) -> CargoResult<bool>
+{
+ walk_inner(path, &mut callback)
+}
+
+fn walk_inner<F>(path: &Path, callback: &mut F) -> CargoResult<()>
+ where F: FnMut(&Path) -> CargoResult<bool>
+{
if path.is_dir() {
let continues = try!(callback(path));
if !continues {
Err(e) => return Err(FromError::from_error(e)),
};
for dir in dirs.iter() {
- try!(walk(dir, |x| callback(x)))
+ try!(walk_inner(dir, callback));
}
}
use std::collections::HashMap;
-use std::c_str::ToCStr;
use std::dynamic_lib::DynamicLibrary;
+use std::ffi::CString;
+use std::path::BytesContainer;
use semver::Version;
use core::{PackageId, Package};
}
/// See `process`.
- pub fn target_process<T: ToCStr>(&self, cmd: T, pkg: &Package)
+ pub fn target_process<T: BytesContainer>(&self, cmd: T, pkg: &Package)
-> CargoResult<CommandPrototype> {
- self.process(CommandType::Target(cmd.to_c_str()), pkg)
+ let cmd = CString::from_slice(cmd.container_as_bytes());
+ self.process(CommandType::Target(cmd), pkg)
}
/// See `process`.
- pub fn host_process<T: ToCStr>(&self, cmd: T, pkg: &Package)
+ pub fn host_process<T: BytesContainer>(&self, cmd: T, pkg: &Package)
-> CargoResult<CommandPrototype> {
- self.process(CommandType::Host(cmd.to_c_str()), pkg)
+ let cmd = CString::from_slice(cmd.container_as_bytes());
+ self.process(CommandType::Host(cmd), pkg)
}
/// Prepares a new process with an appropriate environment to run against
compilation: Compilation::new(root_pkg),
build_state: Arc::new(BuildState::new(build_config.clone(), deps)),
build_config: build_config,
- exec_engine: Arc::new(box ProcessEngine as Box<ExecEngine>),
+ exec_engine: Arc::new(Box::new(ProcessEngine) as Box<ExecEngine>),
})
}
.arg("--crate-name").arg("-")
.arg("--crate-type").arg("dylib")
.arg("--crate-type").arg("bin")
- .arg("--print-file-name");
+ .arg("--print=file-names");
let process = match target {
Some(s) => process.arg("--target").arg(s),
None => process,
fn build_requirements(&mut self, pkg: &'a Package, target: &'a Target,
req: Platform) {
-
let req = if target.get_profile().is_for_host() {Platform::Plugin} else {req};
- match self.requirements.entry(&(pkg.get_package_id(), target.get_name())) {
+ match self.requirements.entry((pkg.get_package_id(), target.get_name())) {
Occupied(mut entry) => match (*entry.get(), req) {
(Platform::Plugin, Platform::Plugin) |
(Platform::PluginAndTarget, Platform::Plugin) |
}
}
- pub fn each_kind(self, f: |Kind|) {
+ pub fn each_kind<F>(self, mut f: F) where F: FnMut(Kind) {
match self {
Platform::Target => f(Kind::Target),
Platform::Plugin => f(Kind::Host),
-use std::c_str::ToCStr;
use std::collections::HashMap;
-use std::fmt;
+use std::ffi::CString;
use std::io::fs::PathExtensions;
use std::io::{fs, USER_RWX, File};
use std::str;
use util::Freshness;
/// Contains the parsed output of a custom build script.
-#[derive(Clone)]
+#[derive(Clone, Show)]
pub struct BuildOutput {
/// Paths to pass to rustc with the `-L` flag
pub library_paths: Vec<Path>,
// Start preparing the process to execute, starting out with some
// environment variables.
let profile = target.get_profile();
- let mut p = try!(super::process(CommandType::Host(to_exec.to_c_str()), pkg, target, cx))
- .env("OUT_DIR", Some(&build_output))
- .env("CARGO_MANIFEST_DIR", Some(pkg.get_manifest_path()
- .dir_path()
- .display().to_string()))
- .env("NUM_JOBS", Some(cx.config.jobs().to_string()))
- .env("TARGET", Some(match kind {
- Kind::Host => cx.config.rustc_host(),
- Kind::Target => cx.target_triple(),
- }))
- .env("DEBUG", Some(profile.get_debug().to_string()))
- .env("OPT_LEVEL", Some(profile.get_opt_level().to_string()))
- .env("PROFILE", Some(profile.get_env()))
- .env("HOST", Some(cx.config.rustc_host()));
+ let to_exec = CString::from_slice(to_exec.as_vec());
+ let p = try!(super::process(CommandType::Host(to_exec), pkg, target, cx));
+ let mut p = p.env("OUT_DIR", Some(&build_output))
+ .env("CARGO_MANIFEST_DIR", Some(pkg.get_manifest_path()
+ .dir_path()
+ .display().to_string()))
+ .env("NUM_JOBS", Some(cx.config.jobs().to_string()))
+ .env("TARGET", Some(match kind {
+ Kind::Host => cx.config.rustc_host(),
+ Kind::Target => cx.target_triple(),
+ }))
+ .env("DEBUG", Some(profile.get_debug().to_string()))
+ .env("OPT_LEVEL", Some(profile.get_opt_level().to_string()))
+ .env("PROFILE", Some(profile.get_env()))
+ .env("HOST", Some(cx.config.rustc_host()));
// Be sure to pass along all enabled features for this package, this is the
// last piece of statically known information that we have.
Ok((library_paths, library_links))
}
}
-
-impl fmt::Show for BuildOutput {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "BuildOutput {{ paths: [..], libs: {}, metadata: {} }}",
- self.library_links, self.metadata)
- }
-}
use std::collections::HashMap;
-use std::c_str::{CString, ToCStr};
+use std::ffi::CString;
+use std::fmt::{self, Formatter};
use std::io::process::ProcessOutput;
-use std::fmt::{self, Show, Formatter};
+use std::path::BytesContainer;
use util::{self, CargoResult, ProcessError, ProcessBuilder};
&self.ty
}
- pub fn arg<T: ToCStr>(mut self, arg: T) -> CommandPrototype {
- self.args.push(arg.to_c_str());
+ pub fn arg<T: BytesContainer>(mut self, arg: T) -> CommandPrototype {
+ self.args.push(CString::from_slice(arg.container_as_bytes()));
self
}
- pub fn args<T: ToCStr>(mut self, arguments: &[T]) -> CommandPrototype {
- self.args.extend(arguments.iter().map(|t| t.to_c_str()));
+ pub fn args<T: BytesContainer>(mut self, arguments: &[T]) -> CommandPrototype {
+ self.args.extend(arguments.iter().map(|t| {
+ CString::from_slice(t.container_as_bytes())
+ }));
self
}
&self.cwd
}
- pub fn env<T: ToCStr>(mut self, key: &str, val: Option<T>) -> CommandPrototype {
- self.env.insert(key.to_string(), val.map(|t| t.to_c_str()));
+ pub fn env<T: BytesContainer>(mut self, key: &str,
+ val: Option<T>) -> CommandPrototype {
+ let val = val.map(|t| CString::from_slice(t.container_as_bytes()));
+ self.env.insert(key.to_string(), val);
self
}
CommandType::Rustc => util::process("rustc"),
CommandType::Rustdoc => util::process("rustdoc"),
CommandType::Target(ref cmd) | CommandType::Host(ref cmd) => {
- util::process(cmd.as_bytes_no_nul())
+ util::process(cmd)
},
});
for arg in self.args.into_iter() {
- builder = builder.arg(arg.as_bytes_no_nul());
+ builder = builder.arg(arg);
}
-
for (key, val) in self.env.into_iter() {
- builder = builder.env(key.as_slice(), val.as_ref().map(|v| v.as_bytes_no_nul()));
+ builder = builder.env(key.as_slice(), val.as_ref());
}
builder = builder.cwd(self.cwd);
}
}
-impl Show for CommandPrototype {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+impl fmt::String for CommandPrototype {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.ty {
CommandType::Rustc => try!(write!(f, "`rustc")),
CommandType::Rustdoc => try!(write!(f, "`rustdoc")),
CommandType::Target(ref cmd) | CommandType::Host(ref cmd) => {
- let cmd = String::from_utf8_lossy(cmd.as_bytes_no_nul());
- try!(write!(f, "`{}", cmd));
+ try!(write!(f, "`{}", String::from_utf8_lossy(cmd.as_bytes())));
},
}
for arg in self.args.iter() {
- try!(write!(f, " {}", String::from_utf8_lossy(arg.as_bytes_no_nul())));
+ try!(write!(f, " {}", String::from_utf8_lossy(arg.as_bytes())));
}
write!(f, "`")
use std::collections::hash_map::Entry::{Occupied, Vacant};
-use std::hash::{Hash, Hasher};
-use std::hash::sip::SipHasher;
+use std::hash::{Hash, Hasher, SipHasher};
use std::io::{self, fs, File, BufferedReader};
use std::io::fs::PathExtensions;
/// from the old directories to their new locations.
pub fn prepare_target(cx: &mut Context, pkg: &Package, target: &Target,
kind: Kind) -> CargoResult<Preparation> {
- let _p = profile::start(format!("fingerprint: {} / {}",
+ let _p = profile::start(format!("fingerprint: {} / {:?}",
pkg.get_package_id(), target));
let new = dir(cx, pkg, kind);
let loc = new.join(filename(target));
} else if target.is_bin() {
cx.compilation.binaries.push(dst);
} else if target.is_lib() {
- let pkgid = pkg.get_package_id();
+ let pkgid = pkg.get_package_id().clone();
match cx.compilation.libraries.entry(pkgid) {
Occupied(entry) => entry.into_mut(),
Vacant(entry) => entry.insert(Vec::new()),
/// Frob in the necessary data from the context to generate the real
/// fingerprint.
-fn mk_fingerprint<T: Hash>(cx: &Context, data: &T) -> String {
- let hasher = SipHasher::new_with_keys(0,0);
- util::to_hex(hasher.hash(&(cx.config.rustc_version(), data)))
+fn mk_fingerprint<T: Hash<SipHasher>>(cx: &Context, data: &T) -> String {
+ let mut hasher = SipHasher::new_with_keys(0,0);
+ (cx.config.rustc_version(), data).hash(&mut hasher);
+ util::to_hex(hasher.finish())
}
fn calculate_target_fresh(pkg: &Package, dep_info: &Path) -> CargoResult<bool> {
impl Work {
pub fn new<F>(f: F) -> Work
where F: FnOnce(Sender<String>) -> CargoResult<()> + Send {
- Work { inner: box f }
+ Work { inner: Box::new(f) }
}
pub fn noop() -> Work {
rx: Receiver<Message>,
resolve: &'a Resolve,
packages: &'a PackageSet,
- active: uint,
+ active: u32,
pending: HashMap<(&'a PackageId, Stage), PendingBuild>,
state: HashMap<&'a PackageId, Freshness>,
ignored: HashSet<&'a PackageId>,
/// A helper structure for metadata about the state of a building package.
struct PendingBuild {
/// Number of jobs currently active
- amt: uint,
+ amt: u32,
/// Current freshness state of this package. Any dirty target within a
/// package will cause the entire package to become dirty.
fresh: Freshness,
config: &Config) -> JobQueue<'a, 'b> {
let (tx, rx) = channel();
JobQueue {
- pool: TaskPool::new(config.jobs()),
+ pool: TaskPool::new(config.jobs() as usize),
queue: DependencyQueue::new(),
tx: tx,
rx: rx,
// Record the freshness state of this package as dirty if any job is
// dirty or fresh otherwise
let fresh = jobs.iter().fold(Fresh, |f1, &(_, f2)| f1.combine(f2));
- match self.state.entry(&pkg.get_package_id()) {
+ match self.state.entry(pkg.get_package_id()) {
Occupied(mut entry) => { *entry.get_mut() = entry.get().combine(fresh); }
Vacant(entry) => { entry.insert(fresh); }
};
loop {
match self.queue.dequeue() {
Some((fresh, (_, stage), (pkg, jobs))) => {
- info!("start: {} {}", pkg, stage);
+ info!("start: {} {:?}", pkg, stage);
try!(self.run(pkg, stage, fresh, jobs, config));
}
None => break,
// of work to finish. If any package fails to build then we stop
// scheduling work as quickly as possibly.
let (id, stage, fresh, result) = self.rx.recv().unwrap();
- info!(" end: {} {}", id, stage);
+ info!(" end: {} {:?}", id, stage);
let id = *self.state.keys().find(|&k| *k == &id).unwrap();
self.active -= 1;
match result {
try!(config.shell().say(
"Build failed, waiting for other \
jobs to finish...", YELLOW));
- for _ in self.rx.iter().take(self.active) {}
+ for _ in self.rx.iter().take(self.active as usize) {}
}
return Err(e)
}
fn run(&mut self, pkg: &'a Package, stage: Stage, fresh: Freshness,
jobs: Vec<(Job, Freshness)>, config: &Config) -> CargoResult<()> {
let njobs = jobs.len();
- let amt = if njobs == 0 {1} else {njobs};
+ let amt = if njobs == 0 {1} else {njobs as u32};
let id = pkg.get_package_id().clone();
// While the jobs are all running, we maintain some metadata about how
}
}
-impl<'a> Dependency<(&'a Resolve, &'a PackageSet)>
- for (&'a PackageId, Stage)
-{
+impl<'a> Dependency for (&'a PackageId, Stage) {
+ type Context = (&'a Resolve, &'a PackageSet);
+
fn dependencies(&self, &(resolve, packages): &(&'a Resolve, &'a PackageSet))
-> Vec<(&'a PackageId, Stage)> {
// This implementation of `Dependency` is the driver for the structure
-use std::c_str::ToCStr;
use std::collections::{HashSet, HashMap};
use std::dynamic_lib::DynamicLibrary;
+use std::ffi::CString;
use std::io::USER_RWX;
use std::io::fs::{self, PathExtensions};
-use std::sync::Arc;
use std::path;
+use std::sync::Arc;
use core::{SourceMap, Package, PackageId, PackageSet, Target, Resolve};
use util::{self, CargoResult, human, caused_human};
return Ok(Compilation::new(pkg))
}
- debug!("compile_targets; targets={}; pkg={}; deps={}", targets, pkg, deps);
+ debug!("compile_targets; targets={:?}; pkg={}; deps={:?}", targets, pkg,
+ deps);
try!(links::validate(deps));
compiled: bool,
cx: &mut Context<'a, 'b>,
jobs: &mut JobQueue<'a, 'b>) -> CargoResult<()> {
- debug!("compile_pkg; pkg={}; targets={}", pkg, targets);
+ debug!("compile_pkg; pkg={}; targets={:?}", pkg, targets);
let _p = profile::start(format!("preparing: {}", pkg));
// Packages/targets which are actually getting compiled are constructed into
// may be building a C lib for a plugin
let layout = cx.layout(pkg, Kind::Target);
let output = layout.native(pkg);
- let mut p = try!(process(CommandType::Host(cmd.next().unwrap().to_c_str()), pkg,
- target, cx))
+ let exe = CString::from_slice(cmd.next().unwrap().as_bytes());
+ let mut p = try!(process(CommandType::Host(exe), pkg, target, cx))
.env("OUT_DIR", Some(&output))
.env("DEPS_DIR", Some(&output))
.env("TARGET", Some(cx.target_triple()))
.env(DynamicLibrary::envvar(), Some(search_path.as_slice())))
}
-fn each_dep<'a>(pkg: &Package, cx: &'a Context, f: |&'a Package|) {
+fn each_dep<'a, F>(pkg: &Package, cx: &'a Context, mut f: F)
+ where F: FnMut(&'a Package)
+{
let mut visited = HashSet::new();
let pkg = cx.get_package(pkg.get_package_id());
- visit_deps(pkg, cx, &mut visited, f);
+ visit_deps(pkg, cx, &mut visited, &mut f);
- fn visit_deps<'a>(pkg: &'a Package, cx: &'a Context,
- visited: &mut HashSet<&'a PackageId>,
- f: |&'a Package|) {
+ fn visit_deps<'a, F>(pkg: &'a Package, cx: &'a Context,
+ visited: &mut HashSet<&'a PackageId>, f: &mut F)
+ where F: FnMut(&'a Package)
+ {
if !visited.insert(pkg.get_package_id()) { return }
f(pkg);
let mut deps = match cx.resolve.deps(pkg.get_package_id()) {
None => return,
};
for dep_id in deps {
- visit_deps(cx.get_package(dep_id), cx, visited, |p| f(p))
+ visit_deps(cx.get_package(dep_id), cx, visited, f);
}
}
}
match opts.to_add {
Some(ref v) => {
let v = v.iter().map(|s| s.as_slice()).collect::<Vec<_>>();
- try!(shell.status("Owner", format!("adding `{:#}` to `{}`", v, name)));
+ try!(shell.status("Owner", format!("adding `{:#?}` to `{}`", v, name)));
try!(registry.add_owners(name.as_slice(), v.as_slice()).map_err(|e| {
human(format!("failed to add owners: {}", e))
}));
match opts.to_remove {
Some(ref v) => {
let v = v.iter().map(|s| s.as_slice()).collect::<Vec<_>>();
- try!(shell.status("Owner", format!("removing `{:#}` from `{}`",
+ try!(shell.status("Owner", format!("removing `{:?}` from `{}`",
v, name)));
try!(registry.remove_owners(name.as_slice(), v.as_slice()).map_err(|e| {
human(format!("failed to add owners: {}", e))
}
pub fn search(query: &str, shell: &mut MultiShell, index: Option<String>) -> CargoResult<()> {
- fn truncate_with_ellipsis(s: &str, max_length: uint) -> String {
+ fn truncate_with_ellipsis(s: &str, max_length: usize) -> String {
if s.len() < max_length {
s.to_string()
} else {
- format!("{}…", s[..max_length - 1])
+ format!("{}…", &s[..max_length - 1])
}
}
use std::fmt::{self, Show, Formatter};
-use std::hash::Hasher;
-use std::hash::sip::SipHasher;
+use std::hash::{Hash, Hasher, SipHasher};
use std::mem;
use url::{self, Url};
}
fn ident(url: &Url) -> String {
- let hasher = SipHasher::new_with_keys(0,0);
+ let mut hasher = SipHasher::new_with_keys(0,0);
// FIXME: this really should be able to not use to_str() everywhere, but the
// compiler seems to currently ask for static lifetimes spuriously.
ident
};
- format!("{}-{}", ident, to_hex(hasher.hash(&url)))
+ url.hash(&mut hasher);
+ format!("{}-{}", ident, to_hex(hasher.finish()))
}
// Some hacks and heuristics for making equivalent URLs hash the same
try!(self.config.shell().status("Updating",
format!("git repository `{}`", self.remote.get_url())));
- log!(5, "updating git source `{}`", self.remote);
+ log!(5, "updating git source `{:?}`", self.remote);
let repo = try!(self.remote.checkout(&self.db_path));
let rev = try!(repo.rev_for(&self.reference));
(repo, rev)
}
fn get(&self, ids: &[PackageId]) -> CargoResult<Vec<Package>> {
- log!(5, "getting packages for package ids `{}` from `{}`", ids, self.remote);
- self.path_source.as_ref().expect("BUG: update() must be called before get()").get(ids)
+ log!(5, "getting packages for package ids `{:?}` from `{:?}`", ids,
+ self.remote);
+ self.path_source.as_ref().expect("BUG: update() must be called \
+ before get()").get(ids)
}
fn fingerprint(&self, _pkg: &Package) -> CargoResult<String> {
-use std::fmt::{self, Show, Formatter};
+use std::fmt::{self, Formatter};
use std::io::{USER_DIR};
use std::io::fs::{mkdir_recursive, rmdir_recursive, PathExtensions};
use rustc_serialize::{Encodable, Encoder};
use core::GitReference;
use util::{CargoResult, ChainError, human, ToUrl, internal};
-#[derive(PartialEq, Clone)]
+#[derive(PartialEq, Clone, Show)]
#[allow(missing_copy_implementations)]
pub struct GitRevision(git2::Oid);
-impl Show for GitRevision {
+impl fmt::String for GitRevision {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- self.0.fmt(f)
+ fmt::String::fmt(&self.0, f)
}
}
url: String,
}
-impl<E, S: Encoder<E>> Encodable<S, E> for GitRemote {
- fn encode(&self, s: &mut S) -> Result<(), E> {
+impl Encodable for GitRemote {
+ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
EncodableGitRemote {
url: self.url.to_string()
}.encode(s)
path: String,
}
-impl<E, S: Encoder<E>> Encodable<S, E> for GitDatabase {
- fn encode(&self, s: &mut S) -> Result<(), E> {
+impl Encodable for GitDatabase {
+ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
EncodableGitDatabase {
remote: self.remote.clone(),
path: self.path.display().to_string()
revision: String,
}
-impl<'a, E, S: Encoder<E>> Encodable<S, E> for GitCheckout<'a> {
- fn encode(&self, s: &mut S) -> Result<(), E> {
+impl<'a> Encodable for GitCheckout<'a> {
+ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
EncodableGitCheckout {
location: self.location.display().to_string(),
revision: self.revision.to_string(),
}
}
-fn with_authentication<T>(url: &str,
- cfg: &git2::Config,
- f: |&mut git2::Credentials| -> CargoResult<T>)
- -> CargoResult<T> {
+fn with_authentication<T, F>(url: &str, cfg: &git2::Config, mut f: F)
+ -> CargoResult<T>
+ where F: FnMut(&mut git2::Credentials) -> CargoResult<T>
+{
// Prepare the authentication callbacks.
//
// We check the `allowed` types of credentials, and we try to do as much as
with_authentication(url, &try!(repo.config()), |f| {
let mut cb = git2::RemoteCallbacks::new();
- cb.credentials(|a, b, c| f.call_mut((a, b, c)));
+ cb.credentials(|a, b, c| f(a, b, c));
let mut remote = try!(repo.remote_anonymous(url.as_slice(),
Some(refspec)));
try!(remote.add_fetch("refs/tags/*:refs/tags/*"));
}
pub fn get_root_package(&self) -> CargoResult<Package> {
- log!(5, "get_root_package; source={}", self);
+ log!(5, "get_root_package; source={:?}", self);
if !self.updated {
return Err(internal("source has not been updated"))
let mut ret = Vec::new();
'outer: for entry in index.iter() {
- let fname = entry.path.as_bytes_no_nul();
+ let fname = entry.path.as_slice();
let file_path = root.join(fname);
// Filter out files outside this package.
}
fn get(&self, ids: &[PackageId]) -> CargoResult<Vec<Package>> {
- log!(5, "getting packages; ids={}", ids);
+ log!(5, "getting packages; ids={:?}", ids);
Ok(self.packages.iter()
.filter(|pkg| ids.iter().any(|id| pkg.get_package_id() == id))
pub struct Config<'a> {
home_path: Path,
shell: RefCell<&'a mut MultiShell>,
- jobs: uint,
+ jobs: u32,
target: Option<string::String>,
rustc_version: string::String,
/// The current host and default target of rustc
impl<'a> Config<'a> {
pub fn new(shell: &'a mut MultiShell,
- jobs: Option<uint>,
+ jobs: Option<u32>,
target: Option<string::String>) -> CargoResult<Config<'a>> {
if jobs == Some(0) {
return Err(human("jobs must be at least 1"))
This probably means that $HOME was not set.")
})),
shell: RefCell::new(shell),
- jobs: jobs.unwrap_or(os::num_cpus()),
+ jobs: jobs.unwrap_or(os::num_cpus() as u32),
target: target,
rustc_version: rustc_version,
rustc_host: rustc_host,
self.shell.borrow_mut()
}
- pub fn jobs(&self) -> uint {
+ pub fn jobs(&self) -> u32 {
self.jobs
}
}
write!(f, "]")
}
- CV::Table(ref table) => write!(f, "{}", table),
+ CV::Table(ref table) => write!(f, "{:?}", table),
CV::Boolean(b, ref path) => {
write!(f, "{} (from {})", b, path.display())
}
}
}
-impl<E, S: Encoder<E>> Encodable<S, E> for ConfigValue {
- fn encode(&self, s: &mut S) -> Result<(), E> {
+impl Encodable for ConfigValue {
+ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
match *self {
CV::String(ref string, _) => string.encode(s),
CV::List(ref list) => {
fn merge(&mut self, from: ConfigValue) -> CargoResult<()> {
match (self, from) {
- (&CV::String(..), CV::String(..)) |
- (&CV::Boolean(..), CV::Boolean(..)) => {}
- (&CV::List(ref mut old), CV::List(ref mut new)) => {
+ (&mut CV::String(..), CV::String(..)) |
+ (&mut CV::Boolean(..), CV::Boolean(..)) => {}
+ (&mut CV::List(ref mut old), CV::List(ref mut new)) => {
let new = mem::replace(new, Vec::new());
old.extend(new.into_iter());
}
- (&CV::Table(ref mut old), CV::Table(ref mut new)) => {
+ (&mut CV::Table(ref mut old), CV::Table(ref mut new)) => {
let new = mem::replace(new, HashMap::new());
for (key, value) in new.into_iter() {
- match old.entry(&key) {
+ match old.entry(key) {
Occupied(mut entry) => { try!(entry.get_mut().merge(value)); }
Vacant(entry) => { entry.insert(value); }
};
}
}
-fn find_in_tree<T>(pwd: &Path,
- walk: |File| -> CargoResult<T>) -> CargoResult<T> {
+fn find_in_tree<T, F>(pwd: &Path, mut walk: F) -> CargoResult<T>
+ where F: FnMut(File) -> CargoResult<T>
+{
let mut current = pwd.clone();
loop {
Err(internal(""))
}
-fn walk_tree(pwd: &Path,
- walk: |File| -> CargoResult<()>) -> CargoResult<()> {
+fn walk_tree<F>(pwd: &Path, mut walk: F) -> CargoResult<()>
+ where F: FnMut(File) -> CargoResult<()>
+{
let mut current = pwd.clone();
loop {
//! it to figure out when a dependency should be built.
use std::collections::hash_set::HashSet;
-use std::collections::hash_map::HashMap;
+use std::collections::hash_map::{HashMap, Hasher};
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::hash::Hash;
}
/// A trait for discovering the dependencies of a piece of data.
-pub trait Dependency<C>: Hash + Eq + Clone {
- fn dependencies(&self, cx: &C) -> Vec<Self>;
+pub trait Dependency: Hash<Hasher> + Eq + Clone {
+ type Context;
+ fn dependencies(&self, cx: &Self::Context) -> Vec<Self>;
}
impl Freshness {
}
}
-impl<C, K: Dependency<C>, V> DependencyQueue<K, V> {
+impl<K: Dependency, V> DependencyQueue<K, V> {
/// Creates a new dependency queue with 0 packages.
pub fn new() -> DependencyQueue<K, V> {
DependencyQueue {
///
/// It is assumed that any dependencies of this package will eventually also
/// be added to the dependency queue.
- pub fn enqueue(&mut self, cx: &C, fresh: Freshness, key: K, value: V) {
+ pub fn enqueue(&mut self, cx: &K::Context, fresh: Freshness, key: K,
+ value: V) {
// ignore self-deps
if self.dep_map.contains_key(&key) { return }
let mut my_dependencies = HashSet::new();
for dep in key.dependencies(cx).into_iter() {
assert!(my_dependencies.insert(dep.clone()));
- let rev = match self.reverse_dep_map.entry(&dep) {
+ let rev = match self.reverse_dep_map.entry(dep) {
Occupied(entry) => entry.into_mut(),
Vacant(entry) => entry.insert(HashSet::new()),
};
}
/// Returns the number of remaining packages to be built.
- pub fn len(&self) -> uint {
+ pub fn len(&self) -> usize {
self.dep_map.len() + self.pending.len()
}
use std::error::{FromError, Error};
-use std::fmt::{self, Show};
+use std::fmt;
use std::io::IoError;
use std::io::process::{ProcessOutput, ProcessExit, ExitStatus, ExitSignal};
use std::str;
fn is_human(&self) -> bool { false }
}
-impl Show for Box<CargoError> {
+impl fmt::String for Box<CargoError> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{}", self.description()));
Ok(())
}
}
+impl fmt::Show for Box<CargoError> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fmt::String::fmt(self, f)
+ }
+}
impl Error for Box<CargoError> {
fn description(&self) -> &str { (**self).description() }
fn chain_error<E2, C>(self, callback: C) -> CargoResult<T>
where E2: CargoError, C: FnOnce() -> E2 {
self.map_err(move |err| {
- box ChainedError {
+ Box::new(ChainedError {
error: callback(),
- cause: box err,
- } as Box<CargoError>
+ cause: Box::new(err),
+ }) as Box<CargoError>
})
}
}
where E: CargoError, C: FnOnce() -> E {
match self {
Some(t) => Ok(t),
- None => Err(box callback() as Box<CargoError>),
+ None => Err(Box::new(callback()) as Box<CargoError>),
}
}
}
}
}
+impl fmt::String for ProcessError {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fmt::String::fmt(&self.desc, f)
+ }
+}
impl fmt::Show for ProcessError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- self.desc.fmt(f)
+ fmt::String::fmt(self, f)
}
}
is_human: bool,
}
-impl fmt::Show for ConcreteCargoError {
+impl fmt::String for ConcreteCargoError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description)
}
}
+impl fmt::Show for ConcreteCargoError {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fmt::String::fmt(self, f)
+ }
+}
impl Error for ConcreteCargoError {
fn description(&self) -> &str { self.description.as_slice() }
pub struct CliError {
pub error: Box<CargoError>,
pub unknown: bool,
- pub exit_code: uint
+ pub exit_code: u32
}
impl Error for CliError {
}
impl CliError {
- pub fn new<S: Str>(error: S, code: uint) -> CliError {
+ pub fn new<S: Str>(error: S, code: u32) -> CliError {
let error = human(error.as_slice().to_string());
CliError::from_boxed(error, code)
}
- pub fn from_error<E: CargoError + 'static>(error: E, code: uint) -> CliError {
- let error = box error as Box<CargoError>;
+ pub fn from_error<E: CargoError + 'static>(error: E, code: u32) -> CliError {
+ let error = Box::new(error) as Box<CargoError>;
CliError::from_boxed(error, code)
}
- pub fn from_boxed(error: Box<CargoError>, code: uint) -> CliError {
+ pub fn from_boxed(error: Box<CargoError>, code: u32) -> CliError {
let human = error.is_human();
CliError { error: error, exit_code: code, unknown: !human }
}
macro_rules! from_error {
($($p:ty,)*) => (
$(impl FromError<$p> for Box<CargoError> {
- fn from_error(t: $p) -> Box<CargoError> { box t }
+ fn from_error(t: $p) -> Box<CargoError> { Box::new(t) }
})*
)
}
}
impl<E: Error> FromError<Human<E>> for Box<CargoError> {
- fn from_error(t: Human<E>) -> Box<CargoError> { box t }
+ fn from_error(t: Human<E>) -> Box<CargoError> { Box::new(t) }
}
impl CargoError for semver::ReqParseError {}
pub fn internal_error<S1: Str, S2: Str>(error: S1,
detail: S2) -> Box<CargoError> {
- box ConcreteCargoError {
+ Box::new(ConcreteCargoError {
description: error.as_slice().to_string(),
detail: Some(detail.as_slice().to_string()),
cause: None,
is_human: false
- }
+ })
}
-pub fn internal<S: Show>(error: S) -> Box<CargoError> {
- box ConcreteCargoError {
+pub fn internal<S: fmt::String>(error: S) -> Box<CargoError> {
+ Box::new(ConcreteCargoError {
description: error.to_string(),
detail: None,
cause: None,
is_human: false
- }
+ })
}
-pub fn human<S: Show>(error: S) -> Box<CargoError> {
- box ConcreteCargoError {
+pub fn human<S: fmt::String>(error: S) -> Box<CargoError> {
+ Box::new(ConcreteCargoError {
description: error.to_string(),
detail: None,
cause: None,
is_human: true
- }
+ })
}
-pub fn caused_human<S: Show, E: Error>(error: S, cause: E) -> Box<CargoError> {
- box ConcreteCargoError {
+pub fn caused_human<S: fmt::String, E: Error>(error: S, cause: E) -> Box<CargoError> {
+ Box::new(ConcreteCargoError {
description: error.to_string(),
detail: None,
- cause: Some(box cause as Box<Error>),
+ cause: Some(Box::new(cause) as Box<Error>),
is_human: true
- }
+ })
}
use std::fmt;
use std::hash::Hash;
use std::collections::hash_set::HashSet;
-use std::collections::hash_map::{HashMap, Keys};
+use std::collections::hash_map::{HashMap, Keys, Hasher};
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::hash_set::Iter;
pub type Nodes<'a, N> = Keys<'a, N, HashSet<N>>;
pub type Edges<'a, N> = Iter<'a, N>;
-impl<N: Eq + Hash + Clone> Graph<N> {
+impl<N: Eq + Hash<Hasher> + Clone> Graph<N> {
pub fn new() -> Graph<N> {
Graph { nodes: HashMap::new() }
}
}
pub fn link(&mut self, node: N, child: N) {
- match self.nodes.entry(&node) {
+ match self.nodes.entry(node) {
Occupied(entry) => entry.into_mut(),
Vacant(entry) => entry.insert(HashSet::new()),
}.insert(child);
}
}
-impl<N: fmt::Show + Eq + Hash> fmt::Show for Graph<N> {
+impl<N: fmt::Show + Eq + Hash<Hasher>> fmt::Show for Graph<N> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(fmt, "Graph {{"));
for (n, e) in self.nodes.iter() {
- try!(writeln!(fmt, " - {}", n));
+ try!(writeln!(fmt, " - {:?}", n));
for n in e.iter() {
- try!(writeln!(fmt, " - {}", n));
+ try!(writeln!(fmt, " - {:?}", n));
}
}
}
}
-impl<N: Eq + Hash> PartialEq for Graph<N> {
+impl<N: Eq + Hash<Hasher>> PartialEq for Graph<N> {
fn eq(&self, other: &Graph<N>) -> bool { self.nodes.eq(&other.nodes) }
}
-impl<N: Eq + Hash> Eq for Graph<N> {}
+impl<N: Eq + Hash<Hasher>> Eq for Graph<N> {}
-impl<N: Eq + Hash + Clone> Clone for Graph<N> {
+impl<N: Eq + Hash<Hasher> + Clone> Clone for Graph<N> {
fn clone(&self) -> Graph<N> {
Graph { nodes: self.nodes.clone() }
}
use std::io::MemWriter;
-use std::hash::{Hasher, Hash};
-use std::hash::sip::SipHasher;
+use std::hash::{Hasher, Hash, SipHasher};
use rustc_serialize::hex::ToHex;
writer.get_ref().to_hex()
}
-pub fn short_hash<H: Hash>(hashable: &H) -> String {
- let hasher = SipHasher::new_with_keys(0, 0);
- to_hex(hasher.hash(hashable))
+pub fn short_hash<H: Hash<SipHasher>>(hashable: &H) -> String {
+ let mut hasher = SipHasher::new_with_keys(0, 0);
+ hashable.hash(&mut hasher);
+ to_hex(hasher.finish())
}
use std::cmp;
-pub fn lev_distance(me: &str, t: &str) -> uint {
+pub fn lev_distance(me: &str, t: &str) -> usize {
if me.is_empty() { return t.chars().count(); }
if t.is_empty() { return me.chars().count(); }
for c in range(0u32, MAX as u32)
.filter_map(|i| from_u32(i))
.map(|i| i.to_string()) {
- assert_eq!(lev_distance(c[], c[]), 0);
+ assert_eq!(lev_distance(&c[], &c[]), 0);
}
let a = "\nMäry häd ä little lämb\n\nLittle lämb\n";
use util::{human, CargoResult};
pub fn realpath(original: &Path) -> io::IoResult<Path> {
- static MAX_LINKS_FOLLOWED: uint = 256;
+ const MAX_LINKS_FOLLOWED: usize = 256;
let original = try!(os::make_absolute(original));
// Right now lstat on windows doesn't work quite well
-use std::fmt::{self, Show, Formatter};
-use std::os;
-use std::c_str::{CString, ToCStr};
-use std::io::process::{Command, ProcessOutput, InheritFd};
use std::collections::HashMap;
+use std::ffi::CString;
+use std::fmt::{self, Formatter};
+use std::io::process::{Command, ProcessOutput, InheritFd};
+use std::os;
+use std::path::BytesContainer;
use util::{CargoResult, ProcessError, process_error};
-#[derive(Clone,PartialEq)]
+#[derive(Clone, PartialEq, Show)]
pub struct ProcessBuilder {
program: CString,
args: Vec<CString>,
cwd: Path,
}
-impl Show for ProcessBuilder {
- fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- try!(write!(f, "`{}", String::from_utf8_lossy(self.program.as_bytes_no_nul())));
+impl fmt::String for ProcessBuilder {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ try!(write!(f, "`{}", String::from_utf8_lossy(self.program.as_bytes())));
for arg in self.args.iter() {
- try!(write!(f, " {}", String::from_utf8_lossy(arg.as_bytes_no_nul())));
+ try!(write!(f, " {}", String::from_utf8_lossy(arg.as_bytes())));
}
write!(f, "`")
}
impl ProcessBuilder {
- pub fn arg<T: ToCStr>(mut self, arg: T) -> ProcessBuilder {
- self.args.push(arg.to_c_str());
+ pub fn arg<T: BytesContainer>(mut self, arg: T) -> ProcessBuilder {
+ self.args.push(CString::from_slice(arg.container_as_bytes()));
self
}
- pub fn args<T: ToCStr>(mut self, arguments: &[T]) -> ProcessBuilder {
- self.args.extend(arguments.iter().map(|t| t.to_c_str()));
+ pub fn args<T: BytesContainer>(mut self, arguments: &[T]) -> ProcessBuilder {
+ self.args.extend(arguments.iter().map(|t| {
+ CString::from_slice(t.container_as_bytes())
+ }));
self
}
self
}
- pub fn env<T: ToCStr>(mut self, key: &str, val: Option<T>) -> ProcessBuilder {
- self.env.insert(key.to_string(), val.map(|t| t.to_c_str()));
+ pub fn env<T: BytesContainer>(mut self, key: &str,
+ val: Option<T>) -> ProcessBuilder {
+ let val = val.map(|t| CString::from_slice(t.container_as_bytes()));
+ self.env.insert(key.to_string(), val);
self
}
}
pub fn build_command(&self) -> Command {
- let mut command = Command::new(self.program.as_bytes_no_nul());
+ let mut command = Command::new(&self.program);
command.cwd(&self.cwd);
for arg in self.args.iter() {
- command.arg(arg.as_bytes_no_nul());
+ command.arg(arg);
}
for (k, v) in self.env.iter() {
let k = k.as_slice();
match *v {
- Some(ref v) => { command.env(k, v.as_bytes_no_nul()); }
+ Some(ref v) => { command.env(k, v); }
None => { command.env_remove(k); }
}
}
}
fn debug_string(&self) -> String {
- let program = String::from_utf8_lossy(self.program.as_bytes_no_nul());
- let mut program = program.to_string();
+ let mut program = format!("{}", String::from_utf8_lossy(self.program.as_bytes()));
for arg in self.args.iter() {
program.push(' ');
- let s = String::from_utf8_lossy(arg.as_bytes_no_nul());
- program.push_str(s.as_slice());
+ program.push_str(&format!("{}", String::from_utf8_lossy(arg.as_bytes()))[]);
}
program
}
}
-pub fn process<T: ToCStr>(cmd: T) -> CargoResult<ProcessBuilder> {
+pub fn process<T: BytesContainer>(cmd: T) -> CargoResult<ProcessBuilder> {
Ok(ProcessBuilder {
- program: cmd.to_c_str(),
+ program: CString::from_slice(cmd.container_as_bytes()),
args: Vec::new(),
cwd: try!(os::getcwd()),
env: HashMap::new(),
use std::os;
use std::mem;
-use std::fmt::Show;
+use std::fmt;
use time;
use std::iter::repeat;
use std::cell::RefCell;
thread_local!(static PROFILE_STACK: RefCell<Vec<u64>> = RefCell::new(Vec::new()));
thread_local!(static MESSAGES: RefCell<Vec<Message>> = RefCell::new(Vec::new()));
-type Message = (uint, u64, String);
+type Message = (usize, u64, String);
pub struct Profiler {
desc: String,
fn enabled() -> bool { os::getenv("CARGO_PROFILE").is_some() }
-pub fn start<T: Show>(desc: T) -> Profiler {
+pub fn start<T: fmt::String>(desc: T) -> Profiler {
if !enabled() { return Profiler { desc: String::new() } }
PROFILE_STACK.with(|stack| stack.borrow_mut().push(time::precise_time_ns()));
let stack_len = PROFILE_STACK.with(|stack| stack.borrow().len());
if stack_len == 0 {
- fn print(lvl: uint, msgs: &[Message]) {
+ fn print(lvl: usize, msgs: &[Message]) {
let mut last = 0;
for (i, &(l, time, ref msg)) in msgs.iter().enumerate() {
if l != lvl { continue }
CryptGetHashParam(self.hcrypthash, HP_HASHVAL, ret.as_mut_ptr(),
&mut len, 0)
});
- assert_eq!(len as uint, ret.len());
+ assert_eq!(len as usize, ret.len());
return ret;
}
}
#[derive(RustcDecodable, Clone, Default)]
#[allow(missing_copy_implementations)]
pub struct TomlProfile {
- opt_level: Option<uint>,
+ opt_level: Option<u32>,
lto: Option<bool>,
- codegen_units: Option<uint>,
+ codegen_units: Option<u32>,
debug: Option<bool>,
rpath: Option<bool>,
}
version: semver::Version,
}
-impl<E, D: Decoder<E>> Decodable<D, E> for TomlVersion {
- fn decode(d: &mut D) -> Result<TomlVersion, E> {
+impl Decodable for TomlVersion {
+ fn decode<D: Decoder>(d: &mut D) -> Result<TomlVersion, D::Error> {
let s = try!(d.read_str());
match s.as_slice().to_semver() {
Ok(s) => Ok(TomlVersion { version: s }),
}
}
-fn process_dependencies<'a>(cx: &mut Context<'a>,
- new_deps: Option<&HashMap<String, TomlDependency>>,
- f: |Dependency| -> Dependency)
- -> CargoResult<()> {
+fn process_dependencies<F>(cx: &mut Context,
+ new_deps: Option<&HashMap<String, TomlDependency>>,
+ mut f: F) -> CargoResult<()>
+ where F: FnMut(Dependency) -> Dependency
+{
let dependencies = match new_deps {
Some(ref dependencies) => dependencies,
None => return Ok(())
benches: &[TomlBenchTarget],
metadata: &Metadata,
profiles: &TomlProfiles) -> Vec<Target> {
- log!(4, "normalizing toml targets; lib={}; bin={}; example={}; test={}, benches={}",
- libs, bins, examples, tests, benches);
-
#[derive(Copy)]
enum TestDep { Needed, NotNeeded }
}
}
- fn bin_targets(dst: &mut Vec<Target>, bins: &[TomlBinTarget],
- dep: TestDep, metadata: &Metadata, profiles: &TomlProfiles,
- default: |&TomlBinTarget| -> String) {
+ fn bin_targets<F>(dst: &mut Vec<Target>, bins: &[TomlBinTarget],
+ dep: TestDep, metadata: &Metadata,
+ profiles: &TomlProfiles,
+ mut default: F)
+ where F: FnMut(&TomlBinTarget) -> String
+ {
for bin in bins.iter() {
let path = bin.path.clone().unwrap_or_else(|| {
PathValue::String(default(bin))
}
}
- fn example_targets(dst: &mut Vec<Target>, examples: &[TomlExampleTarget],
- profiles: &TomlProfiles,
- default: |&TomlExampleTarget| -> String) {
+ fn example_targets<F>(dst: &mut Vec<Target>, examples: &[TomlExampleTarget],
+ profiles: &TomlProfiles,
+ mut default: F)
+ where F: FnMut(&TomlExampleTarget) -> String
+ {
for ex in examples.iter() {
let path = ex.path.clone().unwrap_or_else(|| PathValue::String(default(ex)));
}
}
- fn test_targets(dst: &mut Vec<Target>, tests: &[TomlTestTarget],
- metadata: &Metadata, profiles: &TomlProfiles,
- default: |&TomlTestTarget| -> String) {
+ fn test_targets<F>(dst: &mut Vec<Target>, tests: &[TomlTestTarget],
+ metadata: &Metadata, profiles: &TomlProfiles,
+ mut default: F)
+ where F: FnMut(&TomlTestTarget) -> String
+ {
for test in tests.iter() {
let path = test.path.clone().unwrap_or_else(|| {
PathValue::String(default(test))
}
}
- fn bench_targets(dst: &mut Vec<Target>, benches: &[TomlBenchTarget],
- metadata: &Metadata, profiles: &TomlProfiles,
- default: |&TomlBenchTarget| -> String) {
+ fn bench_targets<F>(dst: &mut Vec<Target>, benches: &[TomlBenchTarget],
+ metadata: &Metadata, profiles: &TomlProfiles,
+ mut default: F)
+ where F: FnMut(&TomlBenchTarget) -> String
+ {
for bench in benches.iter() {
let path = bench.path.clone().unwrap_or_else(|| {
PathValue::String(default(bench))
-#![feature(old_orphan_check)]
+#![allow(unstable)]
extern crate curl;
extern crate "rustc-serialize" as rustc_serialize;
#[derive(RustcDecodable)]
pub struct User {
- pub id: uint,
+ pub id: u32,
pub login: String,
pub avatar: String,
pub email: Option<String>,
MemReader::new(w.into_inner())
};
let tarball = try!(File::open(tarball).map_err(Error::Io));
- let size = stat.size as uint + header.get_ref().len();
- let mut body = ChainedReader::new(vec![box header as Box<Reader>,
- box tarball as Box<Reader>].into_iter());
+ let size = stat.size as usize + header.get_ref().len();
+ let mut body = ChainedReader::new(vec![Box::new(header) as Box<Reader>,
+ Box::new(tarball) as Box<Reader>].into_iter());
let url = format!("{}/api/v1/crates/new", self.host);
Ok(body)
}
-impl fmt::Show for Error {
+impl fmt::String for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::NonUtf8Body => write!(f, "reponse body was not utf-8"),
-#![feature(macro_rules)]
+#![allow(unstable)]
extern crate hamcrest;
extern crate cargo;
], &mut reg);
assert!(res.is_err());
- assert_eq!(res.to_string().as_slice(), "Err(\
+ assert_eq!(res.unwrap_err().to_string(), "\
no package named `foo` found (required by `root`)
location searched: registry http://example.com/
version required: ^1\
-)");
+");
}
#[test]
-use std::c_str::ToCStr;
use std::error::Error;
-use std::fmt::{self, Show};
+use std::fmt;
use std::io::fs::{self, PathExtensions};
use std::io::process::{ProcessOutput};
use std::io;
use std::os;
-use std::path::{Path,BytesContainer};
+use std::path::{Path, BytesContainer};
use std::str::{self, Str};
use url::Url;
self.root.join("target")
}
- pub fn process<T: ToCStr>(&self, program: T) -> ProcessBuilder {
+ pub fn process<T: BytesContainer>(&self, program: T) -> ProcessBuilder {
process(program)
.unwrap()
.cwd(self.root())
fn with_err_msg(self, val: String) -> Result<T, String>;
}
-impl<T, E: Show> ErrMsg<T> for Result<T, E> {
+impl<T, E: fmt::String> ErrMsg<T> for Result<T, E> {
fn with_err_msg(self, val: String) -> Result<T, String> {
match self {
Ok(val) => Ok(val),
expect_stdout: Option<String>,
expect_stdin: Option<String>,
expect_stderr: Option<String>,
- expect_exit_code: Option<int>
+ expect_exit_code: Option<i32>
}
impl Execs {
self
}
- pub fn with_status(mut self, expected: int) -> Execs {
+ pub fn with_status(mut self, expected: i32) -> Execs {
self.expect_exit_code = Some(expected);
self
}
None => ham::success(),
Some(code) => {
ham::expect(
- actual.status.matches_exit_status(code),
+ actual.status.matches_exit_status(code as isize),
format!("exited with {}\n--- stdout\n{}\n--- stderr\n{}",
actual.status,
String::from_utf8_lossy(actual.output.as_slice()),
}
}
-impl fmt::Show for Execs {
+impl fmt::String for Execs {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "execs")
}
expected: String
}
-impl fmt::Show for ShellWrites {
+impl fmt::String for ShellWrites {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "`{}` written to the shell", self.expected)
}
}
}
-pub fn shell_writes<T: Show>(string: T) -> ShellWrites {
+pub fn shell_writes<T: fmt::String>(string: T) -> ShellWrites {
ShellWrites { expected: string.to_string() }
}
pub trait Tap {
- fn tap(mut self, callback: |&mut Self|) -> Self;
+ fn tap<F: FnOnce(&mut Self)>(mut self, callback: F) -> Self;
}
impl<T> Tap for T {
- fn tap(mut self, callback: |&mut T|) -> T {
+ fn tap<F: FnOnce(&mut Self)>(mut self, callback: F) -> T {
callback(&mut self);
self
}
use std::io::IoResult;
use std::io::fs::{self, PathExtensions};
-use std::sync::atomic::{AtomicUint, ATOMIC_UINT_INIT, Ordering};
+use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
use std::{io, os};
use cargo::util::realpath;
static CARGO_INTEGRATION_TEST_DIR : &'static str = "cit";
-static NEXT_ID: AtomicUint = ATOMIC_UINT_INIT;
-thread_local!(static TASK_ID: uint = NEXT_ID.fetch_add(1, Ordering::SeqCst));
+static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT;
+thread_local!(static TASK_ID: usize = NEXT_ID.fetch_add(1, Ordering::SeqCst));
pub fn root() -> Path {
let path = os::self_exe_path().unwrap()
yanked: bool) -> String {
let deps = deps.iter().map(|&(a, b, c)| dep(a, b, c)).collect::<Vec<String>>();
format!("{{\"name\":\"{}\",\"vers\":\"{}\",\
- \"deps\":{},\"cksum\":\"{}\",\"features\":{{}},\
+ \"deps\":[{}],\"cksum\":\"{}\",\"features\":{{}},\
\"yanked\":{}}}",
- name, vers, deps, cksum, yanked)
+ name, vers, deps.connect(","), cksum, yanked)
}
pub fn dep(name: &str, req: &str, kind: &str) -> String {
let p = project("foo")
.file("Cargo.toml", basic_bin_manifest("foo").as_slice())
.file("src/foo.rs", r#"
+ #![allow(unstable)]
extern crate test;
fn hello() -> &'static str {
"hello"
.with_stderr(format!("\
thread '<main>' panicked at 'assertion failed: \
`(left == right) && (right == left)` (left: \
- `hello`, right: `nope`)', src{sep}foo.rs:13
+ `\"hello\"`, right: `\"nope\"`)', src{sep}foo.rs:14
", sep = path::SEP))
.with_status(101));
});
p.cargo_process("build");
- for _ in range(0u, 2) {
+ for _ in range(0, 2) {
assert_that(p.process(cargo_dir().join("cargo")).arg("bench"),
execs().with_status(0));
}
.collect()
}
- let t = Thread::spawn(move|| {
+ let t = Thread::scoped(move|| {
let mut s = BufferedStream::new(a.accept().unwrap());
let req = headers(&mut s);
s.write(b"\
let mut a = listener.listen().unwrap();
let a2 = a.clone();
let _c = Closer { a: a2 };
- let t = Thread::spawn(move|| {
+ let t = Thread::scoped(move|| {
drop(a.accept().unwrap());
});
let mut a = listener.listen().unwrap();
let a2 = a.clone();
let _c = Closer { a: a2 };
- let t = Thread::spawn(move|| {
+ let t = Thread::scoped(move|| {
drop(a.accept().unwrap());
});
name = "bar"
"#)
.file("bar/src/bar.rs", r#"
- pub fn gimme() -> String {
- "test passed".to_string()
+ pub fn gimme() -> &'static str {
+ "test passed"
}
fn dead() {}
fn main() {}
"#)
.file("build.rs", r#"
+ #![allow(unstable)]
fn main() {
std::os::set_exit_status(101);
}
fn setup() {
}
-fn git_repo(name: &str, callback: |ProjectBuilder| -> ProjectBuilder)
- -> Result<ProjectBuilder, ProcessError>
+fn git_repo<F>(name: &str, callback: F) -> Result<ProjectBuilder, ProcessError>
+ where F: FnOnce(ProjectBuilder) -> ProjectBuilder
{
let mut git_project = project(name);
git_project = callback(git_project);
submodule.add_to_index(false).unwrap();
}
let mut index = repo.index().unwrap();
- index.add_all(&["*"], git2::ADD_DEFAULT, Some(|a: &[u8], _b: &[u8]| {
+ index.add_all(["*"].iter(), git2::ADD_DEFAULT,
+ Some((&mut (|&: a: &[u8], _b: &[u8]| {
if s.iter().any(|s| a.starts_with(s.path().as_vec())) {1} else {0}
- })).unwrap();
+ })) as &mut git2::IndexMatchedPath)).unwrap();
index.write().unwrap();
}
name = "foo"
"#, git_project.url()))
.file("src/foo.rs",
- main_file(r#""{}", bar::bar()"#, &["bar"]).as_slice());
+ main_file(r#""{:?}", bar::bar()"#, &["bar"]).as_slice());
// First time around we should compile both foo and bar
assert_that(p.cargo_process("build"),
path = "../bar"
"#)
.file("src/main.rs", r#"
- #![feature(phase)]
- #[phase(plugin)] extern crate bar;
+ #![feature(plugin)]
+ #[plugin] #[no_link] extern crate bar;
extern crate foo_lib;
fn main() { foo_lib::foo(); }
"#)
.file("src/foo_lib.rs", r#"
- #![feature(phase)]
- #[phase(plugin)] extern crate bar;
+ #![feature(plugin)]
+ #[plugin] #[no_link] extern crate bar;
pub fn foo() {}
"#);
crate-type = ["dylib"]
"#)
.file("src/main.rs", r#"
+ #![allow(unstable)]
use std::io::fs;
use std::os;
path = "bar"
"#)
.file("src/main.rs", r#"
- #![feature(phase)]
- #[phase(plugin)] extern crate bar;
+ #![feature(plugin)]
+ #[plugin] #[no_link] extern crate bar;
fn main() {}
"#)
path = "../baz"
"#)
.file("src/main.rs", r#"
- #![feature(phase)]
- #[phase(plugin)]
+ #![feature(plugin)]
+ #[plugin] #[no_link]
extern crate bar;
extern crate baz;
fn main() {
path = "../baz"
"#)
.file("src/main.rs", r#"
- #![feature(phase)]
- #[phase(plugin)]
+ #![feature(plugin)]
+ #[plugin] #[no_link]
extern crate bar;
extern crate baz;
fn main() {
path = "../bar"
"#)
.file("src/main.rs", r#"
- #![feature(phase)]
- #[phase(plugin)] extern crate bar;
+ #![feature(plugin)]
+ #[plugin] #[no_link] extern crate bar;
fn main() {}
"#);
execs().with_status(0));
});
-test!(cross_but_no_dylibs {
- let p = project("foo")
- .file("Cargo.toml", r#"
- [package]
- name = "foo"
- version = "0.0.0"
- authors = []
-
- [lib]
- name = "foo"
- crate-type = ["dylib"]
- "#)
- .file("src/lib.rs", "");
- assert_that(p.cargo_process("build").arg("--target").arg("arm-apple-ios"),
- execs().with_status(101)
- .with_stderr("dylib outputs are not supported for \
- arm-apple-ios"));
-});
-
test!(cross_with_a_build_script {
if disabled() { return }
fn main() {
assert!(os::getenv("OUT_DIR").unwrap()
.contains("target/build/d1-"),
- "bad: {}", os::getenv("OUT_DIR"));
+ "bad: {:?}", os::getenv("OUT_DIR"));
}
"#);
let fname = f.filename_bytes();
assert!(fname == b"foo-0.0.1/Cargo.toml" ||
fname == b"foo-0.0.1/src/main.rs",
- "unexpected filename: {}", f.filename())
+ "unexpected filename: {:?}", f.filename())
}
});
let fname = file.filename_bytes();
assert!(fname == b"foo-0.0.1/Cargo.toml" ||
fname == b"foo-0.0.1/src/main.rs",
- "unexpected filename: {}", file.filename())
+ "unexpected filename: {:?}", file.filename())
}
});
---- test_hello stdout ----
<tab>thread 'test_hello' panicked at 'assertion failed: \
`(left == right) && (right == left)` (left: \
- `hello`, right: `nope`)', src{sep}foo.rs:12
+ `\"hello\"`, right: `\"nope\"`)', src{sep}foo.rs:12
/// ```rust
/// extern crate foo;
/// fn main() {
- /// println!("{}", foo::foo());
+ /// println!("{:?}", foo::foo());
/// }
/// ```
///
p.cargo_process("build");
- for _ in range(0u, 2) {
+ for _ in range(0, 2) {
assert_that(p.process(cargo_dir().join("cargo")).arg("test"),
execs().with_status(0));
}
let config = ShellConfig { color: true, verbose: true, tty: false };
let (tx, mut rx) = pair();
- Shell::create(box tx, config).tap(|shell| {
+ Shell::create(Box::new(tx), config).tap(|shell| {
shell.say("Hey Alex", color::RED).unwrap();
});
let config = ShellConfig { color: false, verbose: true, tty: true };
let (tx, mut rx) = pair();
- Shell::create(box tx, config).tap(|shell| {
+ Shell::create(Box::new(tx), config).tap(|shell| {
shell.say("Hey Alex", color::RED).unwrap();
});
let buf = rx.read_to_end().unwrap();
let config = ShellConfig { color: true, verbose: true, tty: true };
let (tx, mut rx) = pair();
- Shell::create(box tx, config).tap(|shell| {
+ Shell::create(Box::new(tx), config).tap(|shell| {
shell.say("Hey Alex", color::RED).unwrap();
});
let buf = rx.read_to_end().unwrap();
-#![feature(macro_rules, associated_types)]
-#![feature(phase)]
#![deny(warnings)]
+#![allow(unstable)]
extern crate cargo;
extern crate flate2;
extern crate term;
extern crate url;
-#[phase(plugin, link)]
+#[macro_use]
extern crate log;
mod support;